# -*- coding: utf-8 -*-
import bottle
from bottle import (
    default_app,
    request,
    response
)

from .file import (
    file_app,
    templates_dir
)
from .visit import visit_app

from .api import api_app
from .admin import admin_app

bottle.TEMPLATE_PATH.clear()
bottle.TEMPLATE_PATH.append(templates_dir)
main_app = default_app()

main_app.merge(file_app)
main_app.merge(visit_app)

main_app.mount('/api', api_app)
main_app.mount('/admin', admin_app)

DBC = None

_allow_origin = '*'
_allow_methods = 'PUT, GET, POST, DELETE, OPTIONS'
_allow_headers = 'Authorization, Origin, Accept, Content-Type, X-Requested-With'

def setup_db(db_client):
    global DBC
    DBC = db_client

@main_app.hook('before_request')
def check_cors():
    # refer: Response from before_request (https://stackoverflow.com/questions/35530920/response-from-before-request)
    '''
    remoteaddr = request.environ.get('REMOTE_ADDR')
    forwarded = request.environ.get('HTTP_X_FORWARDED_FOR')
    '''
    if request.method.lower() == 'options':
        request.environ['PATH_INFO']= '/cors/'
    if request.method.lower() in ['post', 'delete', 'put', 'get']:
        if not request.path.startswith('/static'):
            global DBC
            DBC.open()
            request.environ['DBC'] = DBC
    print('{0} => {1}'.format(request.method.upper(), request.path))

@main_app.hook('after_request')
def enable_cors():
    if 'DBC' in request.environ:
        global DBC
        DBC.close()
        request.environ.pop('DBC', None)

@main_app.route('/cors/', method='OPTIONS')
def options_handler(path = None):
    '''Add headers to enable CORS'''
    response.headers['Access-Control-Allow-Origin'] = _allow_origin
    response.headers['Access-Control-Allow-Methods'] = _allow_methods
    response.headers['Access-Control-Allow-Headers'] = _allow_headers
    return response

__all__ = [main_app]